<template>
  <view class="container">
    <view class="month-picker">
      <picker mode="date" fields="month" :value="currentMonth" @change="onMonthChange">
        <view class="picker">
          {{currentMonth}}
        </view>
      </picker>
    </view>
    
    <view class="stats-cards">
      <view class="card">
        <text class="card-title">总工时</text>
        <text class="card-value">{{monthlyStats.totalHours}}小时</text>
      </view>
      <view class="card">
        <text class="card-title">工作天数</text>
        <text class="card-value">{{monthlyStats.workdays}}天</text>
      </view>
      <view class="card">
        <text class="card-title">预计工资</text>
        <text class="card-value">¥{{monthlyStats.totalAmount}}</text>
      </view>
    </view>
    
    <view class="period-stats card">
      <view class="section-title">时段分布</view>
      <view class="stats-item" v-for="(stat, period) in periodStats" :key="period">
        <view class="stats-label">
          <text>{{getPeriodText(period)}}</text>
          <text class="stats-hours">{{stat.hours}}小时</text>
        </view>
        <view class="progress-bar">
          <view class="progress" :style="{width: stat.percentage + '%'}"></view>
        </view>
        <text class="percentage">{{stat.percentage}}%</text>
      </view>
    </view>
    
    <view class="daily-stats card">
      <view class="section-title">每日工时</view>
      <scroll-view class="chart-container" scroll-x>
        <view class="chart" :style="{width: dailyStats.length * 80 + 'rpx'}">
          <view class="bar-container" v-for="(stat, index) in dailyStats" :key="index">
            <view class="bar" :style="{height: stat.heightPercentage + '%'}"></view>
            <text class="bar-label">{{stat.date}}</text>
            <text class="bar-value">{{stat.hours}}h</text>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <button class="btn-export" @click="exportData">导出月度报表</button>
  </view>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
  data() {
    return {
      currentMonth: this.formatMonth(new Date()),
      periodStats: {},
      dailyStats: []
    }
  },
  computed: {
    ...mapState(['records']),
    ...mapGetters(['monthlyStats'])
  },
  onShow() {
    this.loadRecords()
    this.calculateStats()
  },
  methods: {
    ...mapActions(['loadRecords', 'setCurrentMonth']),
    
    formatMonth(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      return year + '-' + month
    },
    
    onMonthChange(e) {
      this.currentMonth = e.detail.value
      this.setCurrentMonth(this.currentMonth)
      this.calculateStats()
    },
    
    getPeriodText(period) {
      const texts = {
        morning: '上午',
        afternoon: '下午',
        overtime: '加班'
      }
      return texts[period] || period
    },
    
    calculateStats() {
      // 计算时段统计
      const periodHours = {
        morning: 0,
        afternoon: 0,
        overtime: 0
      }
      
      // 计算每日工时
      const dailyHours = {}
      
      this.records.forEach(record => {
        if (record.date.startsWith(this.currentMonth)) {
          // 累加时段工时
          periodHours[record.period] += parseFloat(record.hours) || 0
          
          // 累加每日工时
          if (!dailyHours[record.date]) {
            dailyHours[record.date] = 0
          }
          dailyHours[record.date] += parseFloat(record.hours) || 0
        }
      })
      
      // 计算时段百分比
      const totalHours = Object.values(periodHours).reduce((sum, hours) => sum + hours, 0)
      this.periodStats = Object.keys(periodHours).reduce((stats, period) => {
        stats[period] = {
          hours: periodHours[period].toFixed(1),
          percentage: totalHours ? Math.round(periodHours[period] / totalHours * 100) : 0
        }
        return stats
      }, {})
      
      // 格式化每日统计数据
      const maxDailyHours = Math.max(...Object.values(dailyHours))
      this.dailyStats = Object.entries(dailyHours)
        .sort(([dateA], [dateB]) => dateA.localeCompare(dateB))
        .map(([date, hours]) => ({
          date: date.split('-')[2], // 只显示日期
          hours: hours.toFixed(1),
          heightPercentage: maxDailyHours ? Math.round(hours / maxDailyHours * 100) : 0
        }))
    },
    
    exportData() {
      // TODO: 实现导出功能
      uni.showToast({
        title: '导出功能开发中',
        icon: 'none'
      })
    }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.month-picker {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
}

.picker {
  text-align: center;
  font-size: 32rpx;
  color: #333;
}

.stats-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.card {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.stats-cards .card {
  width: 30%;
  text-align: center;
}

.card-title {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.card-value {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  display: block;
}

.section-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: bold;
}

.stats-item {
  margin-bottom: 20rpx;
}

.stats-label {
  display: flex;
  justify-content: space-between;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.stats-hours {
  color: #333;
}

.progress-bar {
  height: 10rpx;
  background-color: #f0f0f0;
  border-radius: 5rpx;
  overflow: hidden;
}

.progress {
  height: 100%;
  background-color: #2196f3;
  transition: width 0.3s ease;
}

.percentage {
  font-size: 24rpx;
  color: #999;
  margin-top: 4rpx;
}

.chart-container {
  height: 400rpx;
  white-space: nowrap;
}

.chart {
  height: 100%;
  padding: 20rpx 0;
  display: flex;
  align-items: flex-end;
}

.bar-container {
  width: 60rpx;
  margin: 0 10rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.bar {
  width: 100%;
  background-color: #2196f3;
  border-radius: 6rpx 6rpx 0 0;
  transition: height 0.3s ease;
}

.bar-label {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
}

.bar-value {
  font-size: 20rpx;
  color: #999;
  margin-top: 4rpx;
}

.btn-export {
  margin-top: 40rpx;
  background-color: #2196f3;
  color: #fff;
}
</style>